<script setup lang="ts">
import { ref } from "vue";
import { useMessage, NButton, NInput, NInputGroup, NSpace } from "naive-ui";
import { logout } from "../api/user";
import { removeToken, getToken, listenSetToken, listenRemoveToken } from "../util/token";
import router from "../router";

const message = useMessage();

const isLogon = ref(getToken() != null);
listenSetToken(() => isLogon.value = true);
listenRemoveToken(() => isLogon.value = false);

const handleLogoutButtonClick = async () => {
  const token = getToken();
  if (token) {
    try {
      await logout(token);

      message.success('已经退出登录了', {
        duration: 1000,
        onAfterLeave: () => {
          removeToken();
          window.location.reload();
        },
      });
    } catch (error) {
      console.error(error);
      message.error('出现了点问题，但还是设法登出了 :D', {
        duration: 1500,
        onAfterLeave: () => {
          removeToken();
          window.location.reload();
        },
      });
    }
  }
};

const inputValue = ref('');

const handleSearch = (e: KeyboardEvent | MouseEvent) => {
  if (
    (e instanceof MouseEvent) ||
    (e instanceof KeyboardEvent &&  e.key == 'Enter')
  ) {
    if (inputValue.value.trim() == '') return;
    router.push({ name: 'search', query: { q: inputValue.value.trim() }});
  }
};
</script>

<template>
  <header class="header">
    <h1 class="page-title">
      <router-link to="/">
        淘金
      </router-link>
    </h1>
    <div class="search">
      <n-input-group @keyup="handleSearch">
        <n-input
          v-model:value="inputValue"
          placeholder="搜索商品"
          clearable
        />
        <n-button
          @click="handleSearch"
          type="primary"
        >
          搜索
        </n-button>
      </n-input-group>
    </div>
    <div
      class="user is-logon"
      v-if="isLogon"
    >
      <n-space align="center">
        <p>
            <router-link :to="{ name: 'cart' }">
            购物车
            </router-link>
        </p>
        <p>
            <router-link to="/user">
            我的淘金
            </router-link>
        </p>
        <n-button
            v-if="isLogon"
            :disabled="!isLogon"
            @click="handleLogoutButtonClick"
        >
            注销
        </n-button>  
      </n-space>
    </div>

    <div
      class="user is-not-logon"
      v-else
    >
      <n-space align="center">
        <p>
            <router-link to="/login">
            登录
            </router-link>
        </p>
        <p>
            <router-link to="/register">
            注册
            </router-link>
        </p>
      </n-space>
      
    </div>
  </header>
</template>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 24px;
}
.header .page-title {
  margin: 0;
}
.header .user {
  display: flex;
  align-items: center;
}
</style>
